{% extends '_admin.html' %}

{% set table_name_ch='用戶' %}

{% block main_contain %}
<div class="row" id="ViewData">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
              <div class="btn-group">
                <button type="button" class="btn btn-info" data-toggle="modal" data-target="#AddModal">
                  <i class="fas fa-plus"></i> 新增
                </button>
                <button type="button" class="btn btn-info" data-toggle="modal" data-target="#FilterModal">
                  <i class="fas fa-search"></i> 篩選
                </button>
                <button type="button" class="btn btn-info" @click="reset_filters"><i class="fas fa-undo"></i> 重置</button>
              </div>
            </div>
            <!-- /.card-header -->
            <div class="card-body">
              <table id="UserTable" class="table table-bordered table-hover text-center">
                <thead>
                <tr>
                  {% for k, v in ColumnName.items() %}
                  {% if k not in ('Password') %}
                  <th>{{ v }}</th>
                  {% endif %}
                  {% endfor %}
                  <th>操作</th>
                </tr>
                </thead>
                <tbody>
                    {% if Users %}
                    {% for i in Users %}
                    <tr style="font-size: x-large;">
                      <td>
                        <a href="#" data-toggle="modal" data-target="#EditModal" data-condiction="{{ i.id }}">{{ i.id }}</a>
                      </td>
                      <td>{{ i.LoginName }}</td>
                      <td>{{ i.UserName }}</td>
                      <td>{{ i.Phone }}</td>
                      <td>{{ i.role_description(*Roles) }}</td>
                      <td>{{ i.CashierName }}</td>
                      <td>
                        <button class="btn btn-sm btn-danger" data-toggle="modal" data-target="#DeleteModal" 
                        data-condiction="{{ i.id }}" data-login_name="{{ i.LoginName }}">刪除</button>
                      </td>
                    </tr>
                    {% endfor %}
                    {% endif %}
                </tbody>
              </table>
            </div>
            <!-- /.card-body -->
          </div>
    </div>

  <!--操作对话框-->
  <div class="modal fade" id="AddModal">
      <div class="modal-dialog modal-dialog-centered">
        <form id="AddForm">
          <div class="modal-content">
            <div class="modal-header justify-content-center">
                <h4 class="modal-title text-danger">新增{{ table_name_ch }}</h4>
            </div>
            <div class="modal-body text-center">
              <div v-for="(val, key) in ViewAdd" class="form-group row">
                <label class="col-sm-4 col-form-label text-center">{[ ColumnName[key] ]}：</label>
                <div class="col-sm-8">
                    <select v-if="key=='RoleID'" v-model="ViewAdd[key]" class="form-control" :name="key" style="font-size: large;">
                      {% for r in Roles %}
                      <option value="{{r.id}}">{{r.Description}}</option>
                      {% endfor %}
                    </select>
                    <select v-else-if="key=='CashierName'" v-model="ViewAdd[key]" class="form-control" :name="key" style="font-size: large;">
                      <option value=""></option>
                      {% if Cashiers %}
                      {% for c in Cashiers %}
                      <option value="{{c.CashierName}}">{{c.CashierName}}</option>
                      {% endfor %}
                      {% endif %}
                    </select>
                    <input v-else v-model="ViewAdd[key]" class="form-control" :type="key=='Password'?'password':'text'" :name="key" style="font-size: large;">
                </div>
              </div>
            </div>
            <div class="modal-footer justify-content-between">
                <button type="submit" class="btn btn-success">確認</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </form>
      </div>
    <!-- /.modal-dialog -->
  </div>

  <div class="modal fade" id="EditModal">
    <div class="modal-dialog modal-dialog-centered">
      <form id="EditForm">
        <div class="modal-content">
          <div class="modal-header justify-content-center">
              <h4 class="modal-title text-danger">{{ table_name_ch }}設定</h4>
          </div>
          <div class="modal-body text-center">
            <div v-for="(val, key) in ViewEdit" v-if="key!='UserID'" class="form-group row">
              <label class="col-sm-4 col-form-label text-center">{[ ColumnName[key] ]}：</label>
              <div class="col-sm-8">
                  <select v-if="key=='RoleID'" v-model="ViewEdit[key]" class="form-control" :name="key" style="font-size: large;">
                    {% for r in Roles %}
                    <option value="{{r.id}}">{{r.Description}}</option>
                    {% endfor %}
                  </select>
                  <select v-else-if="key=='CashierName'" v-model="ViewEdit[key]" class="form-control" :name="key" style="font-size: large;">
                    {% if Cashiers %}
                    {% for c in Cashiers %}
                    <option value="{{c.CashierName}}">{{c.CashierName}}</option>
                    {% endfor %}
                    {% endif %}
                  </select>
                  <input v-else v-model="ViewEdit[key]" class="form-control" :type="key=='Password'?'password':'text'" 
                  :readonly="key=='LoginName'?'readonly':false" :name="key" style="font-size: large;">
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-between">
              <button type="submit" class="btn btn-success">確認</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </form>
    </div>
  <!-- /.modal-dialog -->
  </div>

  <div class="modal fade" id="FilterModal">
    <div class="modal-dialog modal-dialog-centered">
      <form id="FilterForm">
        <div class="modal-content">
          <div class="modal-header justify-content-center">
              <h4 class="modal-title text-danger">篩選{{ table_name_ch }}</h4>
          </div>
          <div class="modal-body text-center">
            <div v-for="(val, key) in ViewFilter" class="form-group row">
              <label class="col-sm-4 col-form-label text-center">{[ ColumnName[key] ]}：</label>
              <div class="col-sm-8">
                <select v-if="key=='RoleID'" v-model="ViewFilter[key]" class="select2bs4 select2-hidden-accessible" 
                :name="key" style="font-size: large;width: 100%;" id="role_id_select2">
                  {% for r in Roles %}
                  <option value="{{r.id}}">{{r.Description}}</option>
                  {% endfor %}
                </select>
                <select v-else-if="key=='CashierName'" v-model="ViewAdd[key]" class="select2bs4 select2-hidden-accessible" 
                :name="key" style="font-size: large;width: 100%;" id="cashiers_select2">
                  {% if Cashiers %}
                  {% for c in Cashiers %}
                  <option value="{{c.CashierName}}">{{c.CashierName}}</option>
                  {% endfor %}
                  {% endif %}
                </select>
                <input v-else v-model="ViewFilter[key]" class="form-control" :type="key=='Password'?'password':'text'" :name="key" style="font-size: large;">
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-success" data-dismiss="modal" @click="commit_data('Filter')">查找</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </form>
    </div>
  <!-- /.modal-dialog -->
  </div>

  <div class="modal fade" id="DeleteModal">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
        <div class="modal-header justify-content-center">
            <h4 class="modal-title text-danger"><i class="fas fa-exclamation-triangle"></i> 請注意</h4>
        </div>
        <div class="modal-body text-center">
            <p class="h5">刪除<strong class="text-danger">{[ ViewDelete.LoginName ]}</strong>的用戶嗎？</p>
        </div>
        <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-success" @click="commit_data('Delete')">確認</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        </div>
        </div>
        <!-- /.modal-content -->
    </div>
  <!-- /.modal-dialog -->
  </div>
</div>

<a id="scrobutton" href="#" class="btn btn-primary back-to-top" role="button" aria-label="Scroll to top" style="margin-bottom: 45px; display: none;">
  <i class="fas fa-chevron-up"></i>
</a>
{% endblock %}


{% block scripts %}
{{ super() }}
<script>
    // ViewData
    var ViewData = new Vue({
        el: '#ViewData',
        delimiters: ['{[', ']}'],
        data: {
          ViewAdd: {
            LoginName: '',
            UserName: '',
            Password: '',
            Phone: '',
            RoleID: '',
            CashierName: '',
          },
          ViewEdit: {
            UserID: '',
            LoginName: '',
            UserName: '',
            Password: '',
            Phone: '',
            RoleID: '',
            CashierName: '',
          },
          ViewFilter: {
            LoginName: '',
            UserName: '',
            RoleID: [],
            CashierName: [],
          },
          ViewDelete:{
            UserID: '',
            LoginName: '',
          },
          ColumnName: JSON.parse('{{ ColumnNameJSON|safe }}'),
        },
        methods: {
          // 获取当前数据
          data_select(condition){
            axios.post("{{ url_for('carpark.users') }}", {GetData: condition})
            .then(response => {
              if(response.status==200){
                let ret = response.data
                if(ret.__proto__==Object.prototype){
                  for(key in this.ViewEdit){if(ret.hasOwnProperty(key)){this.ViewEdit[key]=ret[key]}}
                }
              }else{AppMessage.fire({icon: 'error', text: '請求錯誤，請聯係管理員'})}
            })
            .catch(function (error) {alert(error)})
          },
          // 获取当前查询条件
          current_filters(){
            let filters = JSON.parse('{{ UsersFilter|safe }}')
            for(key in this.ViewFilter){if(filters.hasOwnProperty(key)){this.ViewFilter[key]=filters[key]}}
            $("#role_id_select2").val(filters.RoleID).trigger("change")
            $("#cashiers_select2").val(filters.CashierName).trigger("change")
          },
          // 重置
          reset_filters(){
            axios.post("{{ url_for('carpark.users') }}", {ResetFilter: 'UserFilter'})
            .then(response => {if(response.status==200){setTimeout("window.location.reload()")}})
            .catch(function (error) {alert(error)})
          },
          // 筛选条件
          identify_filters(){
            this.ViewFilter.RoleID = []
            this.ViewFilter.CashierName = []
            let roles = $("#role_id_select2").val()
            for(i in roles){if(roles[i]!=''){this.ViewFilter.RoleID.push(parseInt(roles[i]))}}

            let cashiers = $("#cashiers_select2").val()
            for(i in cashiers){if(cashiers[i]!=''){this.ViewFilter.CashierName.push(cashiers[i])}}
            return this.ViewFilter
          },
          // 提交数据
          commit_data(name){
              let p_data = ''
              switch(name){
                case 'Add': p_data={Add: this.ViewAdd};break
                case 'Update': p_data={Update: this.ViewEdit};break
                case 'Delete': p_data={Delete: this.ViewDelete};break
                case 'Filter': p_data={SetFilter: this.identify_filters()};break
              }
              axios.post("{{ url_for('carpark.users') }}", p_data)
              .then(response => {
                if(response.status==200){
                  let ret = response.data
                  AppMessage.fire({icon: ret.icon, text: ret.text})
                  if(ret.icon=='success'){
                    if($('#AddModal').css('display')=="block"){$("#AddModal").modal('toggle')}
                    if($('#EditModal').css('display')=="block"){$("#EditModal").modal('toggle')}
                    if($('#DeleteModal').css('display')=="block"){$("#DeleteModal").modal('toggle')}
                    setTimeout("window.location.reload()", 2000);
                  }
                }else{AppMessage.fire({icon: 'error', text: '操作錯誤，請聯係管理員'})}
              })
              .catch(function (error) {alert(error)})
            }
        },
        mounted: function(){
          // 校验新增
          $('#AddForm').validate({
            rules: {
              LoginName: {required: true},
              UserName: {required: true},
              Password: {required: true, minlength: 6},
              RoleID: {required: true},
            },
            errorElement: 'span',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.col-sm-8').append(error);
              },
            highlight: function (element, errorClass, validClass) {$(element).addClass('is-invalid')},
            unhighlight: function (element, errorClass, validClass) {$(element).removeClass('is-invalid')},
            // 提交
            submitHandler: function (){
              ViewData.commit_data('Add')
            },
          });
          // 校验编辑
          $('#EditForm').validate({
            rules: {
              LoginName: {required: true},
              UserName: {required: true},
              Password: {minlength: 6},
              RoleID: {required: true},
            },
            errorElement: 'span',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.col-sm-8').append(error);
              },
            highlight: function (element, errorClass, validClass) {$(element).addClass('is-invalid')},
            unhighlight: function (element, errorClass, validClass) {$(element).removeClass('is-invalid')},
            // 提交
            submitHandler: function (){
              ViewData.commit_data('Update')
            },
          });
          // 数据表
          $('#UserTable').DataTable({
              language: {url: "{{ url_for('static', filename='plugins/datatables/zh_hk.json') }}"},
              responsive: true,
              autoWidth: false,
            });

          // 编辑設備
          $("#EditModal").on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget) 
            let condiction = button.data('condiction')
            ViewData.data_select(condiction)
          });

          // 删除設備
          $("#DeleteModal").on('show.bs.modal', function (event) {
            let button = $(event.relatedTarget) 
            let condiction = button.data('condiction')
            let login_name = button.data('login_name')
            ViewData.ViewDelete.UserID = condiction
            ViewData.ViewDelete.LoginName = login_name
          });

          // 权限筛选
          $("#role_id_select2").select2({
            placeholder: '選擇權限',
            multiple: true,
            allowClear: true,
            minimumResultsForSearch: false,
            closeOnSelect: false,
            theme: 'bootstrap4'
          });

          // 收费处选择
          $("#cashiers_select2").select2({
            placeholder: '選擇收費處',
            multiple: true,
            allowClear: true,
            minimumResultsForSearch: false,
            closeOnSelect: false,
            theme: 'bootstrap4'
          });
        }
    });
    // 加载筛选值
    $(document).ready(function(){ViewData.current_filters()})
    // 当网页向下滑动 20px 出现"返回顶部" 按钮
    window.onscroll = function() {
      if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {$("#scrobutton").css("display", "block")}
      else {$("#scrobutton").css("display", "none")}
    };
</script>
{% endblock %}

